﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Net;
using wang.Net;
using System.Runtime.CompilerServices;
using CETTest;
using AxShockwaveFlashObjects;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
 
        private AxShockwaveFlash axShockwaveFlash;
        private string qqNum = "2652303993";//"2313166770";2306713395 1936059908
        string pwd = "qwe123";
        private Http urB1;
        private string g_login_sig = string.Empty;
        private Match match;
        private List<QqLoginUser> loginUserList;
        private QQUser user = new QQUser();

        public Form1()
        {
            InitializeComponent();
        }

       
        /// <summary>
        /// 通过正则取文本中间
        /// </summary>
        /// <param name="html"></param>
        /// <param name="regStart"></param>
        /// <param name="regEnd"></param>
        /// <param name="ignoreCase"></param>
        /// <returns></returns>
        public static string GetMiddleText(string html, string regStart, string regEnd, bool ignoreCase)
        {
            string regString = string.Format("{0}(?<getcontent>[\\s|\\S]+?){1}", regStart, regEnd);
            Regex reg;
            if (ignoreCase)
            {
                reg = new Regex(regString, RegexOptions.IgnoreCase);
            }
            else
            {
                reg = new Regex(regString);
            }
            return reg.Match(html).Groups["getcontent"].Value;

        }

        #region ====================QQ网页登录密码的核心算法
        public static string binl2hex(byte[] buffer)
        {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < buffer.Length; i++)
            {
                builder.Append(buffer[i].ToString("x2"));
            }
            return builder.ToString();
        }

        public static string md5(string input)
        {
            byte[] buffer = MD5.Create().ComputeHash(Encoding.GetEncoding("ISO-8859-1").GetBytes(input));
            return binl2hex(buffer);
        }


        public static string hexchar2bin(string passWord)
        {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < passWord.Length; i = i + 2)
            {
                builder.Append(Convert.ToChar(Convert.ToInt32(passWord.Substring(i, 2), 16)));
            }
            return builder.ToString();
        }

        /// <summary>
        /// 获取最新空间加密的方法
        /// </summary>
        /// <param name="uin">http://check.ptlogin2.qq.com/check?uin={0}&appid=15000101&r={1} 返回的第三个值</param>
        /// <param name="password">QQ密码</param>
        /// <param name="verifycode">验证码</param>
        /// <returns></returns>
        public static string GetPassword1(string password, string verifycode, string uin)
        {
            String P = hexchar2bin(md5(password));
            String U = md5(P + hexchar2bin(uin.Replace("\\x", ""))).ToUpper();
            String V = md5(U + verifycode.ToUpper()).ToUpper();
            return V;
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        public static string GetPassword(string qq, string password, string verifycode)
        {
            string str = hexchar2bin(md5(password));
            string str2 = md5(str + hexchar2bin(qq.Replace("\\x", ""))).ToUpper();
            // string ssss = User.md5(str2 + verifycode.ToUpper()).ToUpper();
            return md5(str2 + verifycode.ToUpper()).ToUpper();

        }

        #endregion

        private void Form1_Load(object sender, EventArgs e)
        {
           

        }

        private int g_tk(string str)
        {
            System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
            char[] c = str.ToCharArray();
            int hash = 5381;
            for (int i = 0, len = str.Length; i < len; ++i)
            {

                hash += (hash << 5) + +(int)str.Substring(i, 1).ToCharArray()[0];
 
            }
            return hash & 0x7fffffff;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            button3.Enabled = false;
            user = new QQUser();
            LoginQQgame(qqNum, pwd);
            button3.Enabled = true;
        }

        void axShockwaveFlash_FlashCall(object sender, _IShockwaveFlashEvents_FlashCallEvent e)
        {
             
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //int i = g_tk("@AXsBalCWb");
            button1.Enabled = false;
            string lastQQName = IsLoginQQ();

            if (loginUserList==null)
            {
                loginUserList = new List<QqLoginUser>();
                string path = Path.Combine(Application.StartupPath, "qq.txt"); ;
                StreamReader sr = new StreamReader(path, Encoding.Default);
                string s;

                while ((s = sr.ReadLine()) != null)
                {
                    string[] q = s.Split(' ');
                    q = q.Where(m => !string.IsNullOrEmpty(m)).ToArray();
                    if (q.Length > 1)
                    {

                        if (!string.IsNullOrEmpty(lastQQName) && q[0].Trim() != lastQQName)
                        {
                            continue;
                        }
                        else
                        {
                            lastQQName = "";
                            QqLoginUser user = new QqLoginUser();
                            user.userName = q[0].Trim();
                            user.pwd = q[1].Trim();
                            loginUserList.Add(user);
                        }
                    }
                }
            }

            if (loginUserList.Count > 0)
            {
                bool result = LoginQQgame(loginUserList[0].userName, loginUserList[0].pwd);
                if (result)
                {
                    WriteQQLogin(loginUserList[0].userName);
                    loginUserList.RemoveAt(0);
                    user = new QQUser();
                    this.textBox1.Text = "";
                    if (loginUserList.Count > 0)
                        timer1.Start();
                    else
                    {
                        WriteQQLogin("");
                        button1.Enabled = true;
                        axShockwaveFlash.Visible = false;
                        MessageBox.Show("ok");
                    }
                }
                else
                {
                    button1.Enabled = true;
                    timer1.Stop();
                }
            }
            else
                button1.Enabled = true;

        }

        private void WriteQQLogin(string qqName)
        {
            string path = Path.Combine(Application.StartupPath, "openqq.txt");
            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                //获得字节数组
                byte[] data = new UTF8Encoding().GetBytes(qqName);
                //开始写入
                fs.Write(data, 0, data.Length);
                //清空缓冲区、关闭流
                fs.Flush();
                fs.Close();
            } 
        }

        private string IsLoginQQ()
        {
            string qq = string.Empty;
            string path = Path.Combine(Application.StartupPath, "openqq.txt");
            using (StreamReader sr = new StreamReader(path, Encoding.Default))
            {
                string s;
                while ((s = sr.ReadLine()) != null)
                {
                    qq = s;
                }
            }
            return qq;
        }

        private bool LoginQQgame(string qqName,string qqPwd)
        {
            if (string.IsNullOrEmpty(textBox1.Text))
            {
                urB1 = new Http();

                this.urB1.Get("http://qqapp.qq.com/app/100615799.html#jump=http%3a%2f%2frc.qzone.qq.com%2f100615799");
                string ddd = this.urB1.Get("http://ui.ptlogin2.qq.com/cgi-bin/login?hide_title_bar=1&no_verifyimg=1&link_target=blank&appid=15004501&target=self&s_url=http%3a%2f%2fqzs.qq.com%2fqzone%2fvas%2fapp%2fappstore%2fact%2flogin_jump.html");

                g_login_sig = ddd.Substring(ddd.IndexOf("g_login_sig="));
                g_login_sig = g_login_sig.Replace("g_login_sig=\"", "");
                //g_login_sig = g_login_sig.Substring(0, g_login_sig.IndexOf("\""));
                user.g_login_sig = g_login_sig.Substring(0, g_login_sig.IndexOf("\""));

                urB1.Referer = "http://qzone.qq.com";
                string text2 = this.urB1.Get(string.Format("http://check.ptlogin2.qq.com/check?uin={0}&appid=15004501&js_ver=10024&js_type=0&login_sig={1}&u1=http%3A%2F%2Fqzs.qq.com%2Fqzone%2Fvas%2Fapp%2Fappstore%2Fact%2Flogin_jump.html&r={2}", qqName, user.g_login_sig, new Random().NextDouble()));

                text2 = text2.Replace(" ", "");
                match = new Regex("ptui_checkvc\\('(?<err>\\d+)','(?<code>.*?)','(?<uin>.+?)'", RegexOptions.IgnoreCase).Match(text2);
                if (match.Success)
                {
                    int num = int.Parse(match.Groups["err"].Value);
                    string value = match.Groups["code"].Value;
                    user.uin = match.Groups["uin"].Value;
                    //urB2 = match.Groups["uin"].Value;
                    if (num == 1)
                    {
                        byte[] value2 = this.urB1.Download(string.Format("http://captcha.qq.com/getimage?aid=15000101&r={0}&uin={1}", new Random().NextDouble(), qqName));
                        ImageConverter imageConverter = new ImageConverter();
                        Image image = (Image)imageConverter.ConvertFrom(value2);
                        pictureBox1.Image = image;
                        button1.Enabled = true;
                        return false;
                    }
                    else
                    {
                        textBox1.Text = value;
                    }
                }
            }

            string ssss = this.urB1.Get(string.Format("http://ptlogin2.qq.com/login?u={0}&p={1}&verifycode={2}&aid=15004501&u1=http%3A%2F%2Fqzs.qq.com%2Fqzone%2Fvas%2Fapp%2Fappstore%2Fact%2Flogin_jump.html&h=1&ptredirect=0&ptlang=2052&from_ui=1&dumy=&fp=loginerroralert&action=3-23-34744&mibao_css=&t=2&g=1&js_type=0&js_ver=10024&login_sig={3}", qqName, GetPassword(user.uin, qqPwd, this.textBox1.Text), textBox1.Text, user.g_login_sig));
            match = new Regex("ptuiCB\\('(?<err>\\d+)','(?<err1>\\d+)','(?<code>.*?)','(?<err2>\\d+)','(?<uin>.+?)'", RegexOptions.IgnoreCase).Match(ssss);
            if (match.Success)
            {
                string mes = match.Groups["uin"].Value;
                if (mes.IndexOf("登录成功")<=-1)
                {
                    MessageBox.Show(qqName + ":" + mes);
                    return false;
                }
                string url = match.Groups["code"].Value;
                string text = this.urB1.Get(url);
                var q = this.urB1.Cookies.Where(m => m.name == "uin");
                if (q.Any())
                {
                    string value = q.First().value;
                    int gtk = 0;
                    q = urB1.Cookies.Where(m => m.name == "skey");
                    if (q.Any())
                    {
                        user.skey = q.First().value;
                        gtk = g_tk(user.skey);
                    }

                    text = this.urB1.Get("http://qzs.qq.com/qzone/vas/app/appstore/act/login_jump.html");

                    
                    text = this.urB1.Get("http://pinghot.qq.com/pingd?dm=qqapp.qq.com.hot&url=/app/100615799.html&hottag=app.loginSuc&hotx=9999&hoty=9999&sds=0.3798755145602385");

                    text = this.urB1.Get(string.Format("http://appsupport.qq.com/cgi-bin/qzapps/is_fixapp?uin={0}&uid={1}&appid=100615799&pf=qzone&g_tk={2}", value.Trim('o'), qqName, gtk));
                    text = this.urB1.Get("http://rc.qzone.qq.com/100615799");

                    text = this.urB1.Get(string.Format("http://base.s21.qzone.qq.com/cgi-bin/qzapp/userapp_getuserapp.cgi?uin={0}&type=4&fupdate=1&sd=1&isalpha=0&ic=1&g_tk={1}", qqName, gtk));

                    text = this.urB1.Get(string.Format("http://appframe.qq.com/cgi-bin/qzapps/appframe.cgi?appid=100615799&qz_ver=6&pf=qzone&v=1&g_tk={0}", gtk));
                    text = text.Replace("\n", "").Replace("\"", "");
                    string[] s = text.Split(',');
                    for (int i = 0; i < s.Length; i++)
                    {
                        string[] v = s[i].Split(':');
                        for (int l = 0; l < v.Length; l++)
                        {
                            if (v[0] == "openid")
                            {
                                user.openid = v[1];
                            }
                            if (v[0] == "openkey")
                            {
                                user.openkey = v[1];
                            }
                            if (v[0] == "pfkey")
                            {
                                user.pfkey = v[1];
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(user.openid))
                    {
                        text = this.urB1.Get(string.Format("http://app100615799.openwebgame.qq.com/qzone?qz_height=1200&openid={0}&openkey={1}&pf=qzone&pfkey={2}&qz_ver=6&appcanvas=1&params=", user.openid, user.openkey, user.pfkey));


                        //text = this.urB1.Get(string.Format("http://openwebgame.qq.com/app/login.php?appid=100615799&serverid={1}&action=release&rd={0}&_=1364692534788", new Random().NextDouble(), 7));

                        text = this.urB1.Get(string.Format("http://openwebgame.qq.com/app/login.php?appid=100615799&serverid=7&action=release&rd=0.10310423303746452&_=1364692534788", new Random().NextDouble(), 7));

                        text = text.Replace("\n", "").Replace("\"", "");
                        s = text.Split(',');
                        for (int i = 0; i < s.Length; i++)
                        {
                            string[] v = s[i].Split(':');
                            for (int l = 0; l < v.Length; l++)
                            {
                                if (v[0] == "seqid")
                                {
                                    user.seqid = v[1];
                                }
                                if (v[0] == "serverid")
                                {
                                    user.serverid = v[1];
                                }
                            }
                        }
                        if (!string.IsNullOrEmpty(user.seqid))
                        {

                            urB1.Referer = "http://qzs.qq.com/open/fusion/app_redirect.htm";
                            text = this.urB1.Get(string.Format("http://s{5}.app100615799.qqopenapp.com/?seqid={0}&serverid={5}&platform=qzone&s={1}&qz_height=1200&openid={2}&openkey={3}&pf=qzone&pfkey={4}&qz_ver=6&appcanvas=1&params=", user.seqid, new Random().NextDouble(), user.openid, user.openkey, user.pfkey.Replace("}});", ""), user.serverid));
                            try
                            {
                                string flashvars = text.Substring(text.IndexOf("http://app100615799.imgcache.qzoneapp.com/app100615799/Loading.swf"));
                                flashvars = flashvars.Substring(0, flashvars.IndexOf("\""));
                                string guid = flashvars.Substring(flashvars.LastIndexOf("=") + 1);

                                string uid = text.Substring(text.IndexOf("&uid=") + 5);
                                uid = uid.Substring(0, uid.IndexOf('&'));

                                axShockwaveFlash = new AxShockwaveFlash();
                                axShockwaveFlash.Dock = DockStyle.Fill;
                                panel1.Controls.Add(axShockwaveFlash);
                                axShockwaveFlash.FlashVars = string.Format("author=luke&uid={2}&ran={0}&pf=qzone&via=null&app_custom=null&SNUM={1}&INUM=0", guid, 2, uid);
                                axShockwaveFlash.FlashCall += new _IShockwaveFlashEvents_FlashCallEventHandler(axShockwaveFlash_FlashCall);
                                axShockwaveFlash.Movie = string.Format("http://app100615799.imgcache.qzoneapp.com/app100615799/Loading.swf?myran={0}", guid); ;
                            }
                            catch 
                            {
                                MessageBox.Show("游戏正在维护中...");
                                return false;
                            }
                          
                        }
                        else
                        {
                            MessageBox.Show(qqName + ":" + text);
                            return false;
                        }
                    }
                    else
                    {
                        MessageBox.Show(qqName + ":" + text);
                        return false;
                    }
                }

            }
            return true;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //if (axShockwaveFlash != null)
            //    axShockwaveFlash.Dispose();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            for (int i = 0; i < loginUserList.Count; i++)
            {
                timer1.Stop();
                if (axShockwaveFlash != null)
                {
                    axShockwaveFlash.Dispose();
                }
                
                bool result = LoginQQgame(loginUserList[i].userName, loginUserList[i].pwd);
                if (result)
                {
                    user = new QQUser();
                    WriteQQLogin(loginUserList[i].userName);
                    loginUserList.RemoveAt(i);
                    this.textBox1.Text = "";
                    timer1.Start();
                }
                break; ;
            }

            if (loginUserList.Count == 0)
            {
                timer1.Stop();
                WriteQQLogin("");
                axShockwaveFlash.Visible = false;
                button1.Enabled = true;
                MessageBox.Show("ok");
            }
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            //换验证码
            byte[] value2 = this.urB1.Download(string.Format("http://captcha.qq.com/getimage?aid=15000101&r={0}&uin={1}", new Random().NextDouble(), loginUserList[0].userName));
            ImageConverter imageConverter = new ImageConverter();
            Image image = (Image)imageConverter.ConvertFrom(value2);
            pictureBox1.Image = image;
          
        }
    }
}
